package com.store.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.store.common.Result;
import com.store.dto.RefundApplyRequest;
import com.store.dto.RefundHandleRequest;
import com.store.service.RefundService;
import com.store.vo.RefundRecordVO;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 退货退款控制器
 */
@Slf4j
@RestController
@RequestMapping("/refund")
@RequiredArgsConstructor
public class RefundController {
    
    private final RefundService refundService;
    
    /**
     * 顾客申请退货
     */
    @PostMapping("/apply")
    public Result<Long> applyRefund(@Validated @RequestBody RefundApplyRequest request,
                                     HttpServletRequest httpRequest) {
        try {
            Long userId = getUserId(httpRequest);
            Long refundId = refundService.applyRefund(userId, request);
            return Result.success("退货申请已提交", refundId);
        } catch (Exception e) {
            log.error("申请退货失败", e);
            return Result.error("申请退货失败：" + e.getMessage());
        }
    }
    
    /**
     * 员工/管理员处理退货
     */
    @PutMapping("/{id}/handle")
    public Result<String> handleRefund(@PathVariable Long id,
                                        @Validated @RequestBody RefundHandleRequest request,
                                        HttpServletRequest httpRequest) {
        try {
            Long handlerId = getUserId(httpRequest);
            refundService.handleRefund(handlerId, id, request);
            String message = "approved".equals(request.getStatus()) ? "退货已同意，订单已退款" : "退货已拒绝";
            return Result.success(message);
        } catch (Exception e) {
            log.error("处理退货失败", e);
            return Result.error("处理退货失败：" + e.getMessage());
        }
    }
    
    /**
     * 用户查询自己的退货记录列表
     */
    @GetMapping("/my")
    public Result<List<RefundRecordVO>> getMyRefundList(HttpServletRequest httpRequest) {
        try {
            Long userId = getUserId(httpRequest);
            List<RefundRecordVO> list = refundService.getRefundListByUser(userId);
            return Result.success(list);
        } catch (Exception e) {
            log.error("查询退货记录失败", e);
            return Result.error("查询退货记录失败：" + e.getMessage());
        }
    }
    
    /**
     * 查询所有退货记录（分页）- 员工/管理员
     */
    @GetMapping("/list")
    public Result<IPage<RefundRecordVO>> getRefundList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String status,
            HttpServletRequest httpRequest) {
        try {
            IPage<RefundRecordVO> refundPage = refundService.getRefundList(page, pageSize, status);
            return Result.success(refundPage);
        } catch (Exception e) {
            log.error("查询退货记录失败", e);
            return Result.error("查询退货记录失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取退货详情
     */
    @GetMapping("/{id}")
    public Result<RefundRecordVO> getRefundDetail(@PathVariable Long id, HttpServletRequest httpRequest) {
        try {
            RefundRecordVO refund = refundService.getRefundDetail(id);
            return Result.success(refund);
        } catch (Exception e) {
            log.error("获取退货详情失败", e);
            return Result.error("获取退货详情失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据订单ID查询退货记录
     */
    @GetMapping("/order/{orderId}")
    public Result<RefundRecordVO> getRefundByOrderId(@PathVariable Long orderId, HttpServletRequest httpRequest) {
        try {
            RefundRecordVO refund = refundService.getRefundByOrderId(orderId);
            if (refund == null) {
                return Result.success("该订单没有退货记录", null);
            }
            return Result.success(refund);
        } catch (Exception e) {
            log.error("查询订单退货记录失败", e);
            return Result.error("查询订单退货记录失败：" + e.getMessage());
        }
    }
    
    /**
     * 用户取消退货申请
     */
    @DeleteMapping("/{id}")
    public Result<String> cancelRefund(@PathVariable Long id, HttpServletRequest httpRequest) {
        try {
            Long userId = getUserId(httpRequest);
            refundService.cancelRefund(userId, id);
            return Result.success("退货申请已取消");
        } catch (Exception e) {
            log.error("取消退货申请失败", e);
            return Result.error("取消退货申请失败：" + e.getMessage());
        }
    }
    
    /**
     * 从请求中获取用户ID
     */
    private Long getUserId(HttpServletRequest request) {
        Object userIdObj = request.getAttribute("userId");
        if (userIdObj == null) {
            throw new RuntimeException("未登录或登录已过期");
        }
        return Long.valueOf(userIdObj.toString());
    }
}

